<template>
  <el-button type="success" @click="dialogVisible=true">添加+</el-button>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column type="index" label="序号" width="90" />
    <el-table-column prop="roleName" label="角色名称" width="120" >
      <template v-slot="scope">
        <el-button link @click="get(scope.row.id,scope.row.roleName)"> <u>{{ scope.row.roleName }}</u>    </el-button>
      </template>
    </el-table-column>
    <el-table-column prop="createUserName" label="创建人" width="120" />
    <el-table-column prop="createTime" label="创建时间" width="180" >
      <template v-slot="scope">
       <span>{{ scope.row.createTime==null?"":moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="updateUserName" label="修改人" width="120" />
    <el-table-column prop="updateTime" label="修改时间" width="180" >
       <template v-slot="scope">
         <span>{{ scope.row.updateTime==null?"":moment(scope.row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <el-button  type="danger" size="small" @click="handleClick(scope.row.id)">
          删除
        </el-button>
        <el-button  type="warning" size="small" @click="Update(scope.row)">修改</el-button>
        <el-button  type="primary" size="small" @click="allocation(scope.row.id,scope.row.roleName)" >分配人员</el-button>
      </template>
    </el-table-column>
  </el-table>

<!--添加角色-->
   <el-dialog
    v-model="dialogVisible"
    title="添加"
    width="500"

  >
   <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="角色名称" prop="roleName">
      <el-input v-model="ruleForm.roleName" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        添加
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
<!--修改角色-->
   <el-dialog
    v-model="UndialogVisible"
    title="修改"
    width="500"

  >
 <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="角色名" prop="roleName">
      <el-input v-model="ruleForm.roleName" />
    </el-form-item>
       
    <el-form-item>
      <el-button type="primary" @click="UpdateData()">
        修改
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
<!--分配人员-->
    <el-dialog
    v-model="AlldialogVisible"
    :title="`请设置【${query.roleName}】角色的员工`"
    width="600"
    hight="600"
  >
  <el-row>
    <el-col :span="24">
      <div class="grid-content ep-bg-purple-dark" />
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="12">
      <el-tree
    ref="treeRef"
    style="max-width: 600px"
    class="filter-tree"
    :data="data"
    :props="defaultProps"
    default-expand-all
    :filter-node-method="filterNode"
    @node-click="nodeClick"
  />
    </el-col>
    <el-col :span="12">

           <el-tree
    ref="userTreeRef"
    style="max-width: 600px"
    :data="datauser"
    show-checkbox
    node-key="id"
    :props="defaultProp"
    :default-expand-all="true"
  />
    </el-col >
      <el-button type="primary" @click="Save()" style="float: right; margin-bottom: 150px;">
          确认保存
        </el-button>
</el-row>
  </el-dialog>
<!--属于角色-->
 <el-dialog
    v-model="ShowdialogVisible"
    width="600"
    style="height: 300px"
    :show-close="false"
  >
    <el-row class="role-dialog-container">
      <el-col :span="24" style="margin-left: 500px">
        <el-button link @click="ShowdialogVisible = false"><b>"关闭"</b></el-button>
      </el-col>
      <el-col :span="24" style="margin-top: 50px; margin-left: 150px">
        <span style="margin: auto">{{`属于角色【${query.roleName}】的员工如下:`}}</span>
      </el-col>
      <el-col :span="22" class="user-list-container">
        <div class="user-item" v-for="item in usershow1" :key="item.userId">
          <span class="user-name">{{ item.userName }}</span>
          <el-button type="danger" link @click="DeleteUserRole(item.userId, item.userName)" >×</el-button >
        </div>
      </el-col>
      <el-col :span="2" class="add-user-container">
        <el-button class="add-user-btn" type="success" link @click="all()" ><b>＋</b></el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref ,reactive, onMounted, watch, nextTick} from 'vue'
import { ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { FilterNodeMethodFunction, TreeInstance } from 'element-plus'
import { arEg, id } from 'element-plus/es/locales.mjs'
import  moment  from 'moment'
import http from '../lanjieqi/lan1'
import axios from '../lanjieqi/lan'
//弹出框
const dialogVisible = ref(false)
const UndialogVisible = ref(false)
const AlldialogVisible = ref(false)
const ShowdialogVisible = ref(false)
//分页
const Page=reactive
({
  PageIndex:1,
  PageSize:50,
  totalCount:0,
  totalPage:0
})

//显示
const tableData = ref([])
const seach=()=>
{
  axios.get("api/Role/GetRoleShow",{params:
    {
      PageIndex:Page.PageIndex,
      PageSize:Page.PageSize
    }}).then(res=>
  {
    tableData.value=res.data.data
    Page.totalCount=res.data.totalCount
  })
}
//生命周期函数
onMounted(()=>
{
  seach()

})

//反填角色
const Update=(row:any)=>
{
  UndialogVisible.value=true
  ruleForm.id=row.id
  ruleForm.roleName=row.roleName
}
//修改角色
const UpdateData=()=>
{
  http.put("api/Role/UpdateRole",ruleForm).then(res=>
  {
    if(res.data.code==200)
    {
      ElMessage.success(res.data.message)
      UndialogVisible.value=false
      seach()
    }
    else
    {
      ElMessage.error(res.data.message)
    }
  })
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  roleName: '',
  id:'',
})
//非空验证
const rules = reactive<FormRules>({
  roleName: [
    { required: true, message: '角色名不能为空', trigger: 'blur' },
    { min: 2, max: 15, message: '角色名为2-15个字符', trigger: 'blur' },
  ],
})
//添加角色方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) 
    {
      http.post("api/Role/AddRole",ruleForm).then(res=>
      {
        if(res.data.code==200)
        {
          ElMessage.success(res.data.message)
          dialogVisible.value=false
          ruleForm.roleName=''
          seach()
           
        }
        else
        {
          ElMessage.error(res.data.message)
        }
      })
    } 
    else 
    {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
//删除角色
const handleClick = (id:any) => 
{
   ElMessageBox.confirm(
    '请确认要删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
     http.delete("api/Role/DeleteRole",{params:{id:id}}).then(res=>
     {
      if(res.data.code==200)
      {
        ElMessage.success(res.data.message)
        seach()
      }
      else
      {
        ElMessage.error(res.data.message)
        
      }
     })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//点击部门获取部门下的员工事件
const nodeClick=(x:any)=>
{
  console.log(x);
  
  getuser(x.id)
}
//获取部门下的员工
const datauser=ref([])
const getuser=(id:any)=>
{
  axios.get("api/User/GetUser",{params:{departmentId:id}}).then(res=>
  {
    if(res.data.code==200)
    {
      console.log(res.data.data);
      
      datauser.value=res.data.data
    }
   
  })
}
//显示部门下员工的树形
const defaultProp = {

  id: 'id',
  label: 'userName',
  children: 'children',
}
//分配人员弹框
const allocation=(id:any,rolename:any)=>
{
  query.roleId=id
  query.roleName=rolename
  AlldialogVisible.value=true
  Show(id)   // 反填已分配用户
}

interface Tree {
  [key: string]: any
}
const filterText = ref('')
const treeRef = ref<TreeInstance>()
const userTreeRef = ref<TreeInstance>()
const defaultProps = {
  children: 'children',
  label: 'label',
}
watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
const filterNode: FilterNodeMethodFunction = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}
//部门树形结构
const data: Tree[] = [
  {
    id: 0,
    label: '选择部门',
    children: [
          {
              id: 1,
              label: 'IT信息部',
          },
          {
            id: 2,
            label: '人力资源部',
          },
          {
            id: 3,
            label: '财务部',
          },
          {
            id: 4,
            label: '销售部',
          },
          {
            id: 5,
            label: '行政部',
          },
    ],
  },
]

const query:any=reactive
({
  roleId:'',
  userId:[] as any[],
  roleName:'',
  departmentId:'',
})

//保存分配人员
const Save=()=>
{
  if(newId!=0)
  {
    query.roleId=newId
  }
  query.userId = userTreeRef.value!.getCheckedKeys(false)
  
  http.post("api/Role/AddUserModel",query).then(res=>
  {
    
    if(res.data.code==200)
    {
      ElMessage.success(res.data.message)
      datauser.value=[]
      get(newId,newName)
      ShowdialogVisible.value=false;
      AlldialogVisible.value=false;
    }
    else
    {
      ElMessage.error(res.data.message)
    }
  })
}
const usershow:any=ref([])
//反填分配员工的弹出框数据
const Show=(roleId:any)=>
{
  axios.get("api/Role/GetUserIdsByRoleId",{params:{roleId:roleId}}).then(res=>
  {
    console.log(res.data.data);
  
    if(!res.data.data||!Array.isArray(res.data.data)||res.data.data.length===0)
    {
      query.roleId='';
      query.userId=[];
      usershow.value=[];
      userTreeRef.value?.setCheckedKeys([],true);
      return;
    }
    const data=res.data.data;
    query.roleId=data[0].roleId;
    getuser(data[0].departmentId)
    {
      query.departmentId=data.map((item:any)=>item.departmentId);
    }
    query.userId=data.map((item:any)=>item.userId);
    usershow.value=data.map((item:any)=>item.userName);
    userTreeRef.value?.setCheckedKeys(query.userId,true);
    
  })
}
const usershow1=ref
([{
      "id": '',
      "userId": '',
      "roleId": '',
      "userName": "",
      "departmentId": '',
      "isDeleted": false
}])
//反填属于角色的弹出框数据
const Show1:any=(roleId:any)=>
{
    axios.get("api/Role/GetUserIdsByRoleId",{params:{roleId:roleId}}).then(res=>
    {
      usershow1.value=res.data.data
    })
}

//点击角色的名字的方法
let newName="";
let newId=0
const get=(id:any,name:any)=>
{
  query.roleId=id;
  query.roleName=name;
  newName=name;
  newId=id;
  Show(id);
  Show1(id);
  ShowdialogVisible.value=true;
}
//+号的方法
const all=()=>
{
  allocation(newId,newName)
}
//x号的方法
const DeleteUserRole=(id:any,name:any)=>
{
  ElMessageBox.confirm(
    '确认要删除角色'+newName+'里的用户吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => 
    {
     http.delete("api/Role/DeleteUserRole",{params:{userid:id,roleid:newId}}).then(res=>
     {
       if(res.data.code==200)
       {
         ElMessage.success(res.data.message)
         get(newId,newName);
         return;
       }
       else
       {
         ElMessage.error(res.data.message)
         Show(newId);
         return;
       }
     })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}
</script>
<style>
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

/* 新增用户列表样式 */
.role-dialog-container {
  position: relative;
  min-height: 200px;
}

.user-list-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 20px;
  margin-top: 20px;
  border-right: 1px solid #ebeef5;
}

.add-user-container {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 100%;
  padding-top: 90px;
}

.add-user-btn {
  font-size: 20px;
  height: 40px;
  width: 40px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.user-item {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 5px 10px;
  border-radius: 4px;
  max-width: calc(100% - 20px);
  word-break: break-all;
}

.user-name {
  margin-right: 5px;
  flex: 1;
  overflow-wrap: break-word;
  word-wrap: break-word;
}
</style>






